package com.qilu.pe.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.blankj.utilcode.util.JsonUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.ItemSet;
import com.qilu.pe.dao.bean.ItemSetDetail;
import com.qilu.pe.dao.bean.SetDetail;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.ActiviceCollector;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.ui.fragment.ItemDetail3Fragment;
import com.qilu.pe.ui.fragment.ItemSetDetail1Fragment;
import com.qilu.pe.ui.fragment.ItemSetDetail2Fragment;
import com.qilu.pe.ui.fragment.SetDetail1Fragment;
import com.qilu.pe.ui.fragment.SetDetail2Fragment;
import com.qilu.pe.ui.fragment.SetDetail3Fragment;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.support.view.MeasuredViewPager;
import com.ruitu.arad.util.ToastUtils;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import org.json.JSONArray;
import org.json.JSONObject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 项目/套餐详情 1 项目 2 套餐
public class ItemSetDetailActivity extends Base2Activity {
    private TextView tv_name, tv_price, tv_order;
    private ImageView iv_collct;
    RoundedImageView iv_img;
    private XTabLayout tab_2;
    private MeasuredViewPager vp_tab;
    private LinearLayout ll_adapt;

    private VpTabAdapter vpTabAdapter;// tab
    private String[] HOME_MODELS;

    private String type = "1";// 1 项目 2 套餐
    private String id;// 项目套餐id

    private ItemSetDetail detail;// 请求得到的项目详情
    private SetDetail setDetail;// 请求得到的套餐详情

    private boolean isCollect = false;// 记录收藏状态

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_item_set_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        tab_2 = findViewById(R.id.tab_2);
        vp_tab = findViewById(R.id.vp_tab);
        tv_name = findViewById(R.id.tv_name);
        tv_price = findViewById(R.id.tv_price);
        tv_order = findViewById(R.id.tv_order);
        iv_collct = findViewById(R.id.iv_collct);
        iv_img = findViewById(R.id.iv_img);
        ll_adapt = findViewById(R.id.ll_adapt);

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            id = bundle.getString("id");
            type = bundle.getString("type");
        }

        if (TextUtils.equals("1", type)) {
            setHeadTitle("检测项目");
            HOME_MODELS = new String[]{"项目介绍", "检测样本", "相关疾病"};
        } else {
            setHeadTitle("套餐详情");
            HOME_MODELS = new String[]{"套餐介绍", "检测项目", "检测样本"};
        }

        for (int i = 0; i < 2; i++) {
            tab_2.addTab(tab_2.newTab().setText(HOME_MODELS[i]), i);
        }
        vpTabAdapter = new VpTabAdapter(getSupportFragmentManager());
        vp_tab.setOffscreenPageLimit(9);

        hideProgress();
        if (TextUtils.equals("1", type)) {// 项目
            reqItemSetDetail();
            reqItemCollect("1");// 检测项目是否已收藏
        } else {// 套餐
            reqSetDetail();
            reqSetCollect("1");// 检测套餐是否已收藏
        }
        showProgress();

        setListeners();
    }

    private void setListeners() {
        setOnClickListener(tv_order, iv_collct);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_order) {
            Bundle bundle = new Bundle();
            ItemSet item = new ItemSet();
            //项目
            if ("1".equals(type)) {
                item.setId(id);
                item.setName(detail.getName());
                item.setCode(detail.getCode());
                item.setPicture(detail.getPicture());
                item.setMoney(detail.getPrice());
                item.setPrice(detail.getPrice());
                item.setDay(detail.getDay());
                item.setAdapt(detail.getAdapt());
                item.setHabit(detail.getHabit());
                item.setPurpose(detail.getPurpose());
                item.setSub_id(detail.getSub_id());
                item.setSignificance(detail.getSignificance());
            } else {
                //套餐
                item.setId(id);
                item.setName(setDetail.getName());
                item.setCode(setDetail.getCode());
                item.setPicture(setDetail.getPicture());
                item.setMoney(setDetail.getPrice());
                item.setPrice(setDetail.getPrice());
                item.setDay(setDetail.getDay());
                item.setAdapt(setDetail.getAdapt());
                item.setHabit(setDetail.getHabit());
                item.setSignificance(setDetail.getSignificance());
            }
            startActivity(new Intent(this, PlaceOrderActivity.class)
                    .putExtra("from", "ItemSetDetail")
                    .putExtra("type", type)
                    .putExtra("id", id)
                    .putExtra("item", new Gson().toJson(item)));
        }
        if (v == iv_collct) {
            if (TextUtils.equals("1", type)) {// 项目
                hideProgress();
                reqItemCollect("");
                showProgress();
            } else {// 套餐
                hideProgress();
                reqSetCollect("");
                showProgress();
            }
        }
    }

    // 设置收藏图标
    private void setCollectIcon() {
        if (isCollect) {
            iv_collct.setImageResource(R.mipmap.item_set_detail_collect_icon_2);
        } else {
            iv_collct.setImageResource(R.mipmap.item_set_detail_collect_icon_1);
        }
    }

    private Disposable reqSetDetail() {
        return APIRetrofit.getDefault().reqSetDetail(id)
                .compose(RxUtil.<BaseResult2<SetDetail>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<SetDetail>>() {
                    @Override
                    public void accept(BaseResult2<SetDetail> setResult2) throws Exception {
                        hideProgress();
                        if (setResult2.isSuccess()) {
                            setDetail = setResult2.getData();
                            if (null != setDetail) {
                                vp_tab.setAdapter(vpTabAdapter);
                                tab_2.setupWithViewPager(vp_tab);

                                tv_name.setText(setDetail.getName());
                                tv_price.setText("¥" + setDetail.getPrice());

                                GlideUtil.loadImg(Config.URL_IMG + setDetail.getPicture(), iv_img);

                                loadTagViews(setDetail.getAdapt(), setDetail.getDay());
                            }
                        } else {
                            ToastUtils.showShort(setResult2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqItemSetDetail() {
        return APIRetrofit.getDefault().reqItemSetDetail(id)
                .compose(RxUtil.<BaseResult2<ItemSetDetail>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<ItemSetDetail>>() {
                    @Override
                    public void accept(BaseResult2<ItemSetDetail> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {

                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                        detail = result2.getData();
                        if (null != detail) {
                            vp_tab.setAdapter(vpTabAdapter);
                            tab_2.setupWithViewPager(vp_tab);

                            tv_name.setText(detail.getName());
                            tv_price.setText("¥" + detail.getPrice());

                            GlideUtil.loadImg(Config.URL_IMG + detail.getPicture(), iv_img);

                            loadTagViews(detail.getAdapt(), detail.getDay());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 项目收藏
    private Disposable reqItemCollect(final String type) {
        return APIRetrofit.getDefault().reqProjectCollect(Global.HEADER, type, id)
                .compose(RxUtil.<BaseResult2<List>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List>>() {
                    @Override
                    public void accept(BaseResult2<List> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            if (!TextUtils.isEmpty(type)) {
                                isCollect = true;
                            } else {
                                reqItemCollect("1");
                            }
                        } else {
                            if (!TextUtils.isEmpty(type)) {
                                isCollect = false;
                            } else {
                                reqItemCollect("1");
                            }
                        }
                        setCollectIcon();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        if (!TextUtils.isEmpty(type)) {
                            isCollect = false;
                        }
                        setCollectIcon();
                    }
                });
    }

    // 套餐收藏
    private Disposable reqSetCollect(final String type) {
        return APIRetrofit.getDefault().reqSetCollect(Global.HEADER, type, id)
                .compose(RxUtil.<BaseResult2<List>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List>>() {
                    @Override
                    public void accept(BaseResult2<List> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            if (!TextUtils.isEmpty(type)) {
                                isCollect = true;
                            } else {
                                reqSetCollect("1");
                            }
                        } else {
                            if (!TextUtils.isEmpty(type)) {
                                isCollect = false;
                            } else {
                                reqSetCollect("1");
                            }
                        }
                        setCollectIcon();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        if (!TextUtils.isEmpty(type)) {
                            isCollect = false;
                        }
                        setCollectIcon();
                    }
                });
    }

    private void loadTagViews(List<String> adapt, String day) {
        ll_adapt.removeAllViews();
        for (int i = 0; i < adapt.size(); i++) {
            ll_adapt.addView(createTagView(this, i, getTag(adapt.get(i))));
        }
        ll_adapt.addView(createTagView(this, adapt.size(), day + "个工作日"));
    }

    public TextView createTagView(Context context, int index, String tagStr) {
        TextView tag = new TextView(context);
        tag.setHeight(SizeUtils.dp2px(26f));
        tag.setBackgroundResource(R.drawable.shape_special_tag_bg);
        tag.setGravity(Gravity.CENTER);
        tag.setPadding(SizeUtils.dp2px(10), 0, SizeUtils.dp2px(10), 0);
        tag.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
        tag.setTextSize(14f);
        tag.setText(tagStr);
        if (index > 0) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.leftMargin = SizeUtils.dp2px(10f);
            tag.setLayoutParams(params);
        }
        return tag;
    }

    public String getTag(String tagId) {
        //           0全部,1男性,2女性,3儿童,4青年,5中老年
        switch (tagId) {
            case "0":
                return "全部";
            case "1":
                return "男性";
            case "2":
                return "女性";
            case "3":
                return "儿童";
            case "4":
                return "青年";
            case "5":
                return "中老年";
            default:
                return "";
        }
    }

    // 项目/套餐详情 tab adapter
    private class VpTabAdapter extends FragmentPagerAdapter {

        public VpTabAdapter(@NonNull FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            if (TextUtils.equals("1", type)) {// 项目
                if (position == 0) {
                    return ItemSetDetail1Fragment.newInstance(type, detail);
                } else if (position == 1) {
                    return ItemSetDetail2Fragment.newInstance(type, detail);
                } else if (position == 2) {
                    return ItemDetail3Fragment.newInstance(type, detail);
                } else {
                    return ItemSetDetail1Fragment.newInstance(type, detail);
                }
            } else {// 套餐
                if (position == 0) {
                    return SetDetail1Fragment.newInstance(type, setDetail);
                } else if (position == 1) {
                    return SetDetail2Fragment.newInstance(type, setDetail);
                } else if (position == 2) {
                    return SetDetail3Fragment.newInstance(type, setDetail);
                } else {
                    return SetDetail1Fragment.newInstance(type, setDetail);
                }
            }
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return HOME_MODELS[position];
        }
    }
}